package com.yc.role.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yc.base.BaseServiceImpl;
import com.yc.role.entity.Role;
import com.yc.role.mapper.RoleMapper;
import com.yc.role.service.IRoleService;
import com.yc.user.entity.UserRoleRelation;
import com.yc.user.service.IUserRoleRelationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 后台角色表 服务实现类
 * </p>
 *
 * @author bao
 * @since 2021-12-09
 */
@RequiredArgsConstructor
@Service
public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, Role> implements IRoleService {

    private final IUserRoleRelationService userRoleRelationService;

    @Override
    public boolean create(Role role) {
        return save(role);
    }

    @Override
    public boolean createBatch(List<Role> roleList) {
        return saveBatch(roleList);
    }

    @Override
    public boolean delete(List<Long> ids) {
        return removeByIds(ids);
    }

    @Override
    public boolean update(Role role) {
        return updateById(role);
    }

    @Override
    public Role queryById(Long id) {
        return getById(id);
    }

    @Override
    public List<Role> selectList() {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByDesc(Role::getId);
        return list(wrapper);
    }

    @Override
    public IPage<Role> selectPage(IPage<Role> page) {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByDesc(Role::getId);
        return page(page, wrapper);
    }

    @Override
    public List<Role> queryByUid(Long uid) {
        List<UserRoleRelation> userRoleRelationList = userRoleRelationService.list(Wrappers.lambdaQuery(UserRoleRelation.class)
                .eq(UserRoleRelation::getUserId, uid));
        Set<Long> roleIds = userRoleRelationList.stream().map(UserRoleRelation::getRoleId).collect(Collectors.toSet());
        return list(Wrappers.lambdaQuery(Role.class).in(Role::getId, roleIds));
    }

    @Override
    public List<Role> queryByIds(List<Long> ids) {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.lambda().in(Role::getId, ids);
        return list(wrapper);
    }
}
